<template>
  <div class="search">
    <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索标签"
        @search="onSearch"
        @cancel="onCancel"
    />

  </div>

  <van-button type="primary" @click="doSearch">搜索</van-button>
  <van-divider content-position="left">已选标签</van-divider>

  <van-row gutter="16">

    <van-col v-for="tag in activeIds">

      <van-tag closeable size="medium" type="primary" @close="tagClose(tag)">
        {{ tag }}
      </van-tag>

    </van-col>


  </van-row>


  <van-divider content-position="left">选择标签</van-divider>


  <van-tree-select
      v-model:active-id="activeIds"
      v-model:main-active-index="activeIndex"
      :items="tagList"
  />


</template>


<script setup>
import {ref} from 'vue';
import router from "../router/index.js";
import {getClassListApi, getTagListApi} from "../apis/tagApi.js";
import {onMounted} from "vue";

const searchText = ref();
let originTagList = ref([])


async function getTags() {
  //获取分类
  const resp = await getClassListApi()
  console.log(resp)

  const tagClass = resp.data.data

  //获取子标签
  const resp2 = await getTagListApi()
  const tagList = resp2.data.data

  //将resp和resp2合并成tagList

  originTagList.value = transform(tagClass, tagList)
  console.log(originTagList.value)
}

function transform(tagClass, tagList) {
  console.log(tagClass)
  console.log(tagList)

  return tagClass.map(classItem => {

        const child = tagList.filter(item => item.parentId === classItem.id)
            .map(tag => ({
              text: tag.tagName,
              id: tag.tagName
            }))
        return {
          text: classItem.tagName,
          children: child
        }

      }
  )
}


//组合拼接成标签列表


onMounted(() => {
  getTags()
})


let tagList = ref(originTagList)


const onSearch = () => {
  console.log(searchText.value)

  tagList.value = originTagList.value
      .map(parentTag => {
        //临时存储
        const tempChildren = [...parentTag.children]
        const tempParentTag = {...parentTag}
        tempParentTag.children = tempChildren.filter(item => item.text.includes(searchText.value))
        return tempParentTag;
      })
  console.log("origin{}", originTagList.value)

  console.log(tagList.value)
};


const onCancel = () => {
  searchText.value = ''
  tagList.value = originTagList.value
  console.log(originTagList)
  console.log(tagList.value)
}


const activeIds = ref([]);

const activeIndex = ref(0);

function tagClose(tag) {
  activeIds.value = activeIds.value.filter(item => item !== tag);
}

function doSearch() {
  // 先将要查询的标签列表传入下一个页面，然后下一个页面中查询

  router.push({
    path: '/searchResult',
    query: {
      tags: activeIds.value
    }
  })


  console.log(activeIds.value)
}


</script>

<style scoped>

</style>